<?php

namespace Admin\Controller;

use Think\Model;

/**
 * Description of SpBookproductController
 *
 * @author Myron
 */
class SpBookproductController extends AdminController
{

    /**
     * 展示门店采购列表
     * @author 曹梦龙 <138888611@qq.com>
     */
    public function index()
    {
        $name = I('name');
        $shopId = I('shopId');
        $bookStatus = I('bookStatus');

        if ($shopId > -1) {
            $map['shopId'] = $shopId;
            $this->assign('shopId', $shopId);
        };

        if ($bookStatus > -1) {
            $map['bookStatus'] = $bookStatus;
            $this->assign('bookStatus', $bookStatus);
        };
        $map['batchNum'] = array('like', '%' . (string)$name . '%');
        $list = $this->lists('sp_bookproduct', $map);
        int_to_string($list);
        $this->assign('_list', $list);
        $shoplist = M('sp_shops')->where(array('status' => 1))->select();
        $this->assign('shoplist', $shoplist);
        $this->meta_title = '门店订单清单';
        $this->display();
    }

    /**
     * 展示采购详情
     * @author 曹梦龙 <138888611@qq.com>
     */
    public function detail()
    {
        $id = I('id');
        $BookproductData = M('sp_bookproduct')->where(array('id' => $id))->find();
        $map['bookprodId'] = $id;
        $list = M('table')->table('gr_sp_bookproddetail a,gr_sp_product b')->where('a.productId = b.id and a.bookprodId=' . $id)->field('a.*,b.name as productname')->select();
        int_to_string($list);
        $this->assign('_list', $list);
        $this->assign('data', $BookproductData);
        switch ($BookproductData['bookStatus']) {
            case 0:
                $btnStr = "审核操作";
                break;
            case 10:
                $btnStr = "开始配货";
                break;
            case 30:
                $btnStr = "确认发货";
                break;
        }
        $this->assign('btnStr', $btnStr);
        $this->display();


    }

    /**
     * 状态修改
     * @author 曹梦龙 <138888611@qq.com>
     */
    public function changeStatus($status = '', $id = '', $sendNum = '', $outstockprice = '', $pid = '', $remark = '')
    {
        $gr_sp_bookproduct = array(
            'bookStatus' => $status,
            'remark' => $remark,
        );
        if ($status == 30) {
            for ($i = 0; $i < count($pid); $i++) {
                M('sp_bookproddetail')->where(array('id' => $pid[$i]))->save(array('sendNum' => $sendNum[$i], 'subtotal' => $outstockprice[$i] * $sendNum[$i]));
            }
        }
        if (!M('sp_bookproduct')->where(array('id' => $id))->save($gr_sp_bookproduct)) {
            $this->error('操作失败！');
        } else {
            $this->success('操作成功！');
        };
    }


    /******************采购订单申请******************/
    /**
     * 展示门店选择
     * @author 曹梦龙 <138888611@qq.com>
     */
    public function addindex()
    {
        $shoplist = M('sp_shops')->where(array('status' => 1))->select();
        $this->assign('shoplist', $shoplist);
        $this->meta_title = '门店采购清单';
        $this->display();
    }

    /**
     * 展示门店采购列表
     * @author 曹梦龙 <138888611@qq.com>
     */
    public function addindexshop($shopId = '')
    {
        $name = I('name');
        $shopId = I('shopId');
        $bookStatus = I('bookStatus');

        if ($shopId > -1) {
            $map['shopId'] = $shopId;
            $this->assign('shopId', $shopId);
        };

        if ($bookStatus > -1) {
            $map['bookStatus'] = $bookStatus;
            $this->assign('bookStatus', $bookStatus);
        };
        $map['batchNum'] = array('like', '%' . (string)$name . '%');
        $list = $this->lists('sp_bookproduct', $map);
        int_to_string($list);
        $this->assign('_list', $list);
        $shoplist = M('sp_shops')->where(array('status' => 1))->select();
        $this->assign('shoplist', $shoplist);
        $this->meta_title = '门店订单清单';
        $this->display();
    }

    /**
     * 展示门店采购列表
     * @author 曹梦龙 <138888611@qq.com>
     */
    function add($shopId = '', $remark = "", $caigouList = '')
    {
        if (IS_POST) {
            $caigouArray = json_decode($caigouList);
            $gr_sp_bookproduct = array(
                'shopId' => $shopId,
                'batchNum' => NOW_TIME,
                'bookStatus' => 0,
                'createby' => UID,
                'createat' => NOW_TIME,
                'remark' => $remark,
                'status' => 1,
            );
            $bookprodId = M('sp_bookproduct')->add($gr_sp_bookproduct);
            if (!$bookprodId) {
                $result = array('code' => -1, 'msg' => '订货单创建失败！');
                $this->ajaxReturn($result);
            } else {
                for ($i = 0; $i < count($caigouArray); $i++) {
                    $gr_sp_bookproddetail = array(
                        'bookprodId' => $bookprodId,
                        'productId' => $caigouArray[$i]->pid,
                        'bookNum' => $caigouArray[$i]->number,
                        'unit' => $caigouArray[$i]->unit,
                        'outstockprice' => $caigouArray[$i]->price,
                        'subtotal' => $caigouArray[$i]->amountprice,
                        'status' => 1,
                    );
                    M('sp_bookproddetail')->add($gr_sp_bookproddetail);
                }
                $result = array('code' => 1, 'msg' => '订货单创建成功！');
                $this->ajaxReturn($result);
            };

        } else {
            $map['status'] = 1;
            $pcategorylist = M('sp_pcategory')->where($map)->order('type')->select();
            int_to_string($pcategorylist);
            $this->assign('_pcategorylist', $pcategorylist);
            $this->assign('shopId', $shopId);
            $this->display();
        }
    }




    /********Ajax****/
    /*
     * 获取分类下的商品列表
     */
    function getProductListAjax($cid = '')
    {
        $productList = M('sp_product')->where(array('pCategoryId' => $cid))->order('createat DESC')->select();
        for ($i = 0; $i < count($productList); $i++) {
            $productList[$i]['cnt'] = get_vinventory_count($productList[$i]['code']);
        }
        $this->ajaxReturn($productList);
    }


    /********Ajax****/
    /*
     * 获取分类下的商品列表
     */
    function getProductListBySearchAjax($text = '')
    {

        $map['name'] = array('like', '%' . $text . '%');
        $productList = M('sp_product')->where($map)->select();
        for ($i = 0; $i < count($productList); $i++) {
            $productList[$i]['cnt'] = get_vinventory_count($productList[$i]['code']);
        }
        $this->ajaxReturn($productList);
    }



    /********Ajax****/
    /*
     * 订货单创建后看详情
     */
    function adddetail($id = '')
    {
        $id = I('id');
        $BookproductData = M('sp_bookproduct')->where(array('id' => $id))->find();
        $map['bookprodId'] = $id;
        $list = M('table')->table('gr_sp_bookproddetail a,gr_sp_product b')->where('a.productId = b.id and a.bookprodId=' . $id)->field('a.*,b.name as productname')->select();
        int_to_string($list);
        $this->assign('_list', $list);
        $this->assign('data', $BookproductData);
        switch ($BookproductData['bookStatus']) {
            case 0:
                $btnStr = "审核操作";
                break;
            case 10:
                $btnStr = "开始配货";
                break;
            case 30:
                $btnStr = "确认发货";
                break;
        }
        $this->assign('btnStr', $btnStr);
        $this->display();

    }

    /*
     * 打印预览
     */
    public function printf($id = '')
    {
        $id = I('id');
        $BookproductData = M('sp_bookproduct')->where(array('id' => $id))->find();
        $map['bookprodId'] = $id;
        $list = M('table')->table('gr_sp_bookproddetail a,gr_sp_product b')->where('a.productId = b.id and a.bookprodId=' . $id)->field('a.*,b.name as productname')->select();
        int_to_string($list);
        $sumshuliang = M('sp_bookproddetail')->where(array('bookprodId' => $id))->Sum('sendNum');
        $sumjine = M('sp_bookproddetail')->where(array('bookprodId' => $id))->Sum('subtotal');
        $this->assign('_list', $list);
        $this->assign('data', $BookproductData);
        $this->assign('sumshuliang', $sumshuliang);
        $this->assign('sumjine', $sumjine);
        $this->assign('nowtime', time_format(NOW_TIME));
        $this->display();
    }

    public function  bookProductTotal()
    {
        $bookTotal = $this->bookTotal();
        $this->assign("_list", $bookTotal);

        $this->display("bookproducttotal");

    }

    private function  bookTotal()
    {
        //将审核过的订货进行汇总
        $Model = new Model();
        $sql = "select p.id,p.name,sum(bd.bookNum) booNums from gr_sp_bookproduct b inner join gr_sp_bookproddetail bd on b.id=bd.bookprodId inner join gr_sp_product p on bd.productId=p.id WHERE b.bookStatus=10 and b.status=1 and b.delFlag=0 GROUP  by p.id,p.name";
        $bookTotal = $Model->query($sql);

        $sqlSub = "select p.id,b.shopId,sum(bd.bookNum) booNums from gr_sp_bookproduct b inner join gr_sp_bookproddetail bd on b.id=bd.bookprodId inner join gr_sp_product p on bd.productId=p.id WHERE b.bookStatus=10 and b.status=1 and b.delFlag=0 GROUP  by p.id,b.shopId order by b.shopId asc";
        $bookSub = $Model->query($sqlSub);

        $temp = [];
        for ($i = 0; $i < count($bookTotal); $i++) {
            $tempItem = [$bookTotal[$i]["id"], $bookTotal[$i]["name"], $bookTotal[$i]["booNums"], "0", "0", "0", "0", "0", "0"];
            for ($j = 0; $j < count($bookSub); $j++) {
                if ($bookTotal[$i]["id"] == $bookSub[$j]["id"]) {
                    if ($bookSub[$j]["shopId"] == 2) {
                        $tempItem[3] = $bookSub[$j]["booNums"];
                    } else if ($bookSub[$j]["shopId"] == 3) {
                        $tempItem[4] = $bookSub[$j]["booNums"];
                    } else if ($bookSub[$j]["shopId"] == 4) {
                        $tempItem[5] = $bookSub[$j]["booNums"];
                    } else if ($bookSub[$j]["shopId"] == 5) {
                        $tempItem[6] = $bookSub[$j]["booNums"];
                    } else if ($bookSub[$j]["shopId"] == 6) {
                        $tempItem[7] = $bookSub[$j]["booNums"];
                    } else if ($bookSub[$j]["shopId"] == 7) {
                        $tempItem[8] = $bookSub[$j]["booNums"];
                    } else if ($bookSub[$j]["shopId"] == 8) {
                        $tempItem[9] = $bookSub[$j]["booNums"];
                    }
                }
            }
            $temp[] = $tempItem;
        }
        return $temp;
    }

    public function ExportBookTotal()
    {
        if (!IS_POST) {
            $this->redirect("SpBookproduct/bookProductTotal");
        } else {
            $bookTotal = $this->bookTotal();
            if ($bookTotal) {
                for ($i = 0; $i < count($bookTotal); $i++) {
                    unset($bookTotal[$i]["id"]);
                    unset($bookTotal[$i][0]);
                }
                //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
                import("Org.Util.PHPExcel");
                import("Org.Util.PHPExcel.Writer.Excel5");
                import("Org.Util.PHPExcel.IOFactory.php");

                $filename = "已审核订货汇总表";

                $headArr = array("商品名称", "总订货量", "京华城店", "梅岭店", "望月路店", "三盛店", "时代店", "虹桥坊店", "彩虹汇店");

                $title = "已审核订货汇总表";
                $this->getExcel($filename, $headArr, $bookTotal, $title);
            } else {
                $this->error("没有可导出的数据！");
            }
        }
    }

    /**
     * 导出共用方法
     */
    public function getExcel($fileName, $headArr, $data, $title)
    {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);

        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $key += 1;
        }

        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
//                $objActSheet->getColumnDimension('a')->setWidth(20);
                $objActSheet->getColumnDimension('a')->setWidth(50);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
}
